<template>
  <div class="iChat">
    <div class="container">
      <div class="content">

        <div class="item item-center"><span>{{ formatRealTime() }}</span></div>
<!--        <div class="item item-center"><span>昨天 12:35</span></div>-->
        <div class="item" v-for="(item, index) in receivedMessage" :key="index" :class="{'item-right':isCurrentUser(item),'item-left':!isCurrentUser(item)}">
          <!-- 右结构 -->
          <div v-if="isCurrentUser(item)" style="display: flex">
            <div class="bubble" :class="{'bubble-right':isCurrentUser(item),'bubble-left':!isCurrentUser(item)}">{{item.message}}</div>
            <div class="avatar">
              <img
                  src="https://ts1.cn.mm.bing.net/th/id/R-C.4fb814bf3889e0906f86e8985d3f995e?rik=DTtrRT01QslGWg&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fw%2f2020%2f06-13%2f85303%2fwater_85303_698_698_.png&ehk=ah3XedFm1TEu8yK0Y%2f%2byAXlfocUNSR9vMsdOle9aOaw%3d&risl=&pid=ImgRaw&r=0"
              />
              {{item.userId}}
            </div>
          </div>
          <!-- 左结构 -->
          <div v-else style="display: flex">
            <div class="avatar">
              {{item.userId}}
              <img
                  src="https://p.qqan.com/up/2020-8/15979703206228498.jpg"
              />
            </div>
            <div class="bubble" :class="{'bubble-right':isCurrentUser(item),'bubble-left':!isCurrentUser(item)}">{{item.message}}</div>
          </div>
        </div>
      </div>
      <div class="input-area">
        <!-- 文本框 -->
        <textarea v-model="message" id="textarea"></textarea>
        <div class="button-area">
          <button id="send-btn" @click="sendMessage()">发 送</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {jwtDecode} from "jwt-decode";

export default {
  data() {
    return {
      ws:null,
      message:'',
      receivedMessage:[],
      userId: null
    };
  },
  mounted() {
    this.initWebSocket()
  },
  methods: {

    formatRealTime() {
      const now = new Date();
      const hours = now.getHours().toString().padStart(2, '0');
      const minutes = now.getMinutes().toString().padStart(2, '0');
      // 判断是否为今天，若为今天显示“HH:mm”，否则显示“yyyy-MM-dd HH:mm”
      const isToday = now.toDateString() === new Date().toDateString();
      if (isToday) {
        return `${hours}:${minutes}`;
      } else {
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      }
    },


    //建立webSocket连接
    initWebSocket(){
      //获取token
      const token = sessionStorage.getItem("token");
      if (!token) {
        console.error("未登录，无法建立WebSocket连接");
        this.$router.push('/login'); // 未登录则跳转到登录页
        return;
      }
      //定义用户的，并加入到下述链接中，且记不要少了/
      this.userId = this.parseUserIdFromToken(token);
      //链接接口
      this.ws = new WebSocket('ws://localhost:8080/chatWebSocket/' + this.userId)

      //打开事件
      this.ws.onopen = function(){
        console.log("websocket已打开");
      }

      //消息事件
      this.ws.onmessage = (event) => {
        //接到后端传来数据 - 并对其解析
        this.receivedMessage.push(JSON.parse(event.data));
        console.log(this.receivedMessage)
      }

      //关闭事件
      this.ws.onclose = function() {
        console.log("websocket已关闭");
      };

      //错误事件
      this.ws.onerror = function() {
        console.log("websocket发生了错误");
      };

    },
    //发送消息到服务器
    sendMessage(){
      this.ws.send(this.message);
      this.message = '';
    },
    //判断是否是当前用户(boolean值)
    isCurrentUser(item){
      return item.userId == this.userId
    },
    parseUserIdFromToken(token) {
      const decoded = jwtDecode(token);
      return decoded.userId;
    }
  },
};
</script>
<style lang="scss" scoped>
.container{
  height: 666px;
  border-radius: 4px;
  border: 0.5px solid #e0e0e0;
  background-color: #f5f5f5;
  display: flex;
  flex-flow: column;
  overflow: hidden;
}
.content{
  width: calc(100% - 40px);
  padding: 20px;
  overflow-y: scroll;
  flex: 1;
}
.content:hover::-webkit-scrollbar-thumb{
  background:rgba(0,0,0,0.1);
}
.bubble{
  max-width: 400px;
  padding: 10px;
  border-radius: 5px;
  position: relative;
  color: #000;
  word-wrap:break-word;
  word-break:normal;
}
.item-left .bubble{
  margin-left: 15px;
  background-color: #fff;
}
.item-left .bubble:before{
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-top: 10px solid transparent;
  border-right: 10px solid #fff;
  border-bottom: 10px solid transparent;
  left: -20px;
}
.item-right .bubble{
  margin-right: 15px;
  background-color: #9eea6a;
}
.item-right .bubble:before{
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border-left: 10px solid #9eea6a;
  border-top: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid transparent;
  right: -20px;
}
.item{
  margin-top: 15px;
  display: flex;
  width: 100%;
}
.item.item-right{
  justify-content: flex-end;
}
.item.item-center{
  justify-content: center;
}
.item.item-center span{
  font-size: 12px;
  padding: 2px 4px;
  color: #fff;
  background-color: #dadada;
  border-radius: 3px;
  -moz-user-select:none; /*火狐*/
  -webkit-user-select:none; /*webkit浏览器*/
  -ms-user-select:none; /*IE10*/
  -khtml-user-select:none; /*早期浏览器*/
  user-select:none;
}

.avatar img{
  width: 42px;
  height: 42px;
  border-radius: 50%;
}
.input-area{
  border-top:0.5px solid #e0e0e0;
  height: 150px;
  display: flex;
  flex-flow: column;
  background-color: #fff;
}
textarea{
  flex: 1;
  padding: 5px;
  font-size: 14px;
  border: none;
  cursor: pointer;
  overflow-y: auto;
  overflow-x: hidden;
  outline:none;
  resize:none;
}
.button-area{
  display: flex;
  height: 40px;
  margin-right: 10px;
  line-height: 40px;
  padding: 5px;
  justify-content: flex-end;
}
.button-area button{
  width: 80px;
  border: none;
  outline: none;
  border-radius: 4px;
  float: right;
  cursor: pointer;
}

/* 设置滚动条的样式 */
::-webkit-scrollbar {
  width:10px;
}
/* 滚动槽 */
::-webkit-scrollbar-track {
  border-radius:8px;
}
/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  border-radius:10px;
  background:rgba(0,0,0,0);
}
</style>






<!--<template>-->
<!--  <div class="iChat">-->
<!--    <div class="container">-->
<!--      <div class="content">-->
<!--        <div class="item item-center"><span>昨天 12:35</span></div>-->
<!--        <div class="item item-left">-->
<!--          <div class="avatar">-->
<!--            <img-->
<!--                src="https://p.qqan.com/up/2020-8/15979703206228498.jpg"-->
<!--            />-->
<!--          </div>-->
<!--          <div class="bubble bubble-left">你发一个<br />刚刚网卡了</div>-->
<!--        </div>-->
<!--        <div class="item item-right">-->
<!--          <div class="bubble bubble-right">可以<br />一会儿再发给你 +  {{receivedMessage}}</div>-->
<!--          <div class="avatar">-->
<!--            <img-->
<!--                src="https://ts1.cn.mm.bing.net/th/id/R-C.4fb814bf3889e0906f86e8985d3f995e?rik=DTtrRT01QslGWg&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fw%2f2020%2f06-13%2f85303%2fwater_85303_698_698_.png&ehk=ah3XedFm1TEu8yK0Y%2f%2byAXlfocUNSR9vMsdOle9aOaw%3d&risl=&pid=ImgRaw&r=0"-->
<!--            />-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--      <div class="input-area">-->
<!--        &lt;!&ndash; 文本框 &ndash;&gt;-->
<!--        <textarea v-model="message" id="textarea"></textarea>-->
<!--        <div class="button-area">-->
<!--          <button id="send-btn" @click="sendMessage()">发 送</button>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
<!--  </div>-->
<!--</template>-->

<!--<script>-->
<!--export default {-->
<!--  data() {-->
<!--    return {-->
<!--      ws:null,-->
<!--      message:'',-->
<!--      receivedMessage:'',-->
<!--    };-->
<!--  },-->
<!--  mounted() {-->
<!--    this.initWebSocket()-->
<!--  },-->
<!--  methods: {-->
<!--    //建立webSocket连接-->
<!--    initWebSocket(){-->

<!--      //1.定义用户的，并加入到下述链接中，且记不要少了/-->
<!--      // 定义随机用户用来模拟用户链接-->
<!--      const userId = "用户1" + Math.floor(Math.random() * 1000)-->
<!--      //链接接口-->
<!--      this.ws = new WebSocket('ws://localhost:8080/chatWebSocket/' + userId)-->

<!--      //打开事件-->
<!--      this.ws.onopen = function(){-->
<!--        console.log("websocket已打开");-->
<!--      }-->

<!--      //消息事件-->
<!--      this.ws.onmessage = (event) => {-->
<!--        this.receivedMessage = event.data;-->
<!--      }-->

<!--      //关闭事件-->
<!--      this.ws.onclose = function() {-->
<!--        console.log("websocket已关闭");-->
<!--      };-->

<!--      //错误事件-->
<!--      this.ws.onerror = function() {-->
<!--        console.log("websocket发生了错误");-->
<!--      };-->

<!--    },-->




<!--    //发送消息到服务器-->
<!--    sendMessage(){-->
<!--      this.ws.send(this.message);-->
<!--      this.message = '';-->
<!--    }-->
<!--  },-->
<!--};-->
<!--</script>-->
























<!--<template>-->
<!--  <div class="iChat">-->
<!--    <div class="container">-->
<!--      <div class="content">-->
<!--        <div class="item item-center"><span>昨天 12:35</span></div>-->
<!--        <div class="item item-left">-->
<!--          <div class="avatar">-->
<!--            <img-->
<!--                src="https://p.qqan.com/up/2020-8/15979703206228498.jpg"-->
<!--            />-->
<!--          </div>-->
<!--          <div class="bubble bubble-left">你发一个<br />刚刚网卡了</div>-->
<!--        </div>-->
<!--        <div class="item item-right">-->
<!--          <div class="bubble bubble-right">可以<br />一会儿再发给你 +  {{receivedMessage}}</div>-->
<!--          <div class="avatar">-->
<!--            <img-->
<!--                src="https://ts1.cn.mm.bing.net/th/id/R-C.4fb814bf3889e0906f86e8985d3f995e?rik=DTtrRT01QslGWg&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fw%2f2020%2f06-13%2f85303%2fwater_85303_698_698_.png&ehk=ah3XedFm1TEu8yK0Y%2f%2byAXlfocUNSR9vMsdOle9aOaw%3d&risl=&pid=ImgRaw&r=0"-->
<!--            />-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->
<!--      <div class="input-area">-->
<!--        &lt;!&ndash; 文本框 &ndash;&gt;-->
<!--        <textarea v-model="message" id="textarea"></textarea>-->
<!--        <div class="button-area">-->
<!--          <button id="send-btn" @click="sendMessage()">发 送</button>-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->
<!--  </div>-->
<!--</template>-->

<!--<script>-->
<!--export default {-->
<!--  data() {-->
<!--    return {-->
<!--      //4.赋值存储 ws-->
<!--      ws:null,-->
<!--      message:'',-->
<!--      receivedMessage:'',-->
<!--    };-->
<!--  },-->
<!--  mounted() {-->
<!--    //2.挂载-->
<!--    this.initWebSocket()-->
<!--  },-->
<!--  methods: {-->
<!--    //1.建立webSocket连接-->
<!--    initWebSocket(){-->

<!--      //3.建立链接接口-->
<!--      this.ws = new WebSocket('ws://localhost:8080/chatWebSocket')-->


<!--      //5.消息事件 ( 通过赋值 ws 消息事件 )-->
<!--      this.ws.onmessage = (event) => {-->
<!--        this.receivedMessage = event.data;-->
<!--      }-->

<!--    },-->


<!--    //6.发送消息到服务器-->
<!--    sendMessage(){-->
<!--      this.ws.send(this.message);-->
<!--      this.message = '';-->
<!--    }-->


<!--  },-->
<!--};-->
<!--</script>-->
<!--<style lang="scss" scoped>-->
<!--.container{-->
<!--  height: 666px;-->
<!--  border-radius: 4px;-->
<!--  border: 0.5px solid #e0e0e0;-->
<!--  background-color: #f5f5f5;-->
<!--  display: flex;-->
<!--  flex-flow: column;-->
<!--  overflow: hidden;-->
<!--}-->
<!--.content{-->
<!--  width: calc(100% - 40px);-->
<!--  padding: 20px;-->
<!--  overflow-y: scroll;-->
<!--  flex: 1;-->
<!--}-->
<!--.content:hover::-webkit-scrollbar-thumb{-->
<!--  background:rgba(0,0,0,0.1);-->
<!--}-->
<!--.bubble{-->
<!--  max-width: 400px;-->
<!--  padding: 10px;-->
<!--  border-radius: 5px;-->
<!--  position: relative;-->
<!--  color: #000;-->
<!--  word-wrap:break-word;-->
<!--  word-break:normal;-->
<!--}-->
<!--.item-left .bubble{-->
<!--  margin-left: 15px;-->
<!--  background-color: #fff;-->
<!--}-->
<!--.item-left .bubble:before{-->
<!--  content: "";-->
<!--  position: absolute;-->
<!--  width: 0;-->
<!--  height: 0;-->
<!--  border-left: 10px solid transparent;-->
<!--  border-top: 10px solid transparent;-->
<!--  border-right: 10px solid #fff;-->
<!--  border-bottom: 10px solid transparent;-->
<!--  left: -20px;-->
<!--}-->
<!--.item-right .bubble{-->
<!--  margin-right: 15px;-->
<!--  background-color: #9eea6a;-->
<!--}-->
<!--.item-right .bubble:before{-->
<!--  content: "";-->
<!--  position: absolute;-->
<!--  width: 0;-->
<!--  height: 0;-->
<!--  border-left: 10px solid #9eea6a;-->
<!--  border-top: 10px solid transparent;-->
<!--  border-right: 10px solid transparent;-->
<!--  border-bottom: 10px solid transparent;-->
<!--  right: -20px;-->
<!--}-->
<!--.item{-->
<!--  margin-top: 15px;-->
<!--  display: flex;-->
<!--  width: 100%;-->
<!--}-->
<!--.item.item-right{-->
<!--  justify-content: flex-end;-->
<!--}-->
<!--.item.item-center{-->
<!--  justify-content: center;-->
<!--}-->
<!--.item.item-center span{-->
<!--  font-size: 12px;-->
<!--  padding: 2px 4px;-->
<!--  color: #fff;-->
<!--  background-color: #dadada;-->
<!--  border-radius: 3px;-->
<!--  -moz-user-select:none; /*火狐*/-->
<!--  -webkit-user-select:none; /*webkit浏览器*/-->
<!--  -ms-user-select:none; /*IE10*/-->
<!--  -khtml-user-select:none; /*早期浏览器*/-->
<!--  user-select:none;-->
<!--}-->

<!--.avatar img{-->
<!--  width: 42px;-->
<!--  height: 42px;-->
<!--  border-radius: 50%;-->
<!--}-->
<!--.input-area{-->
<!--  border-top:0.5px solid #e0e0e0;-->
<!--  height: 150px;-->
<!--  display: flex;-->
<!--  flex-flow: column;-->
<!--  background-color: #fff;-->
<!--}-->
<!--textarea{-->
<!--  flex: 1;-->
<!--  padding: 5px;-->
<!--  font-size: 14px;-->
<!--  border: none;-->
<!--  cursor: pointer;-->
<!--  overflow-y: auto;-->
<!--  overflow-x: hidden;-->
<!--  outline:none;-->
<!--  resize:none;-->
<!--}-->
<!--.button-area{-->
<!--  display: flex;-->
<!--  height: 40px;-->
<!--  margin-right: 10px;-->
<!--  line-height: 40px;-->
<!--  padding: 5px;-->
<!--  justify-content: flex-end;-->
<!--}-->
<!--.button-area button{-->
<!--  width: 80px;-->
<!--  border: none;-->
<!--  outline: none;-->
<!--  border-radius: 4px;-->
<!--  float: right;-->
<!--  cursor: pointer;-->
<!--}-->

<!--/* 设置滚动条的样式 */-->
<!--::-webkit-scrollbar {-->
<!--  width:10px;-->
<!--}-->
<!--/* 滚动槽 */-->
<!--::-webkit-scrollbar-track {-->
<!--  -webkit-box-shadow:inset006pxrgba(0,0,0,0.3);-->
<!--  border-radius:8px;-->
<!--}-->
<!--/* 滚动条滑块 */-->
<!--::-webkit-scrollbar-thumb {-->
<!--  border-radius:10px;-->
<!--  background:rgba(0,0,0,0);-->
<!--  -webkit-box-shadow:inset006pxrgba(0,0,0,0.5);-->
<!--}-->
<!--</style>-->
